import os
import subprocess
import re
import sys
import time

pattern = re.compile(r"([^\s]+\.zarr)(?:\s*\[exist\])$")


def create_symlink(log_file):
    with open(log_file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            match = pattern.search(line)
            if match:
                path = match.group(1)
                if "ee" in path:
                    new_path = path.replace("ee", "qpos")
                    if os.path.islink(new_path) or os.path.exists(new_path):
                        print(f"已存在: {new_path}")
                        continue
                    print(f"创建软链接: {new_path} -> {path}")
                    subprocess.run(["ln", "-s", path, new_path], check=True)


def main():
    if len(sys.argv) < 2:
        print("用法: python3 ee2qpos.py xxx")
        sys.exit(1)
    pxyaml = sys.argv[1].strip()
    # 用 bash -c 保证 conda activate 生效
    cmd = (
        "source ~/anaconda3/etc/profile.d/conda.sh && "
        "conda activate 3dpidm && "
        "cd /home/algo/geyiheng/utilgyh && "
        f"python3 create_tmux.py {pxyaml} > {pxyaml}.log"
    )
    log_file = f"{pxyaml}.log"
    try:
        subprocess.run(["bash", "-c", cmd], check=True)
        print(f"已运行: {cmd}")
    except Exception as e:
        print(f"命令执行失败: {e}")

    time.sleep(10)
    create_symlink(log_file)


if __name__ == "__main__":
    main()
